const winston = require('winston');
const path = require('path');
const { format } = winston;
const DailyRotateFile = require('winston-daily-rotate-file');

// 过滤敏感信息
const sensitiveFields = ['password', 'token', 'access_token', 'openid'];
const sensitiveDataFilter = format((info) => {
    if (info.message && typeof info.message === 'object') {
        for (const key of Object.keys(info.message)) {
            if (sensitiveFields.includes(key.toLowerCase())) {
                info.message[key] = '***REDACTED***';
            }
        }
    }
    return info;
});

const logger = winston.createLogger({
    level: process.env.LOG_LEVEL || 'info',
    format: format.combine(
        sensitiveDataFilter(),
        format.timestamp({
            format: 'YYYY-MM-DD HH:mm:ss.SSS'
        }),
        format.errors({ stack: true }),
        format.json()
    ),
    transports: [
        // 错误日志 - 按天轮转
        new DailyRotateFile({
            level: 'error',
            filename: path.join(__dirname, '../logs/error-%DATE%.log'),
            datePattern: 'YYYY-MM-DD',
            zippedArchive: true,
            maxSize: '20m',
            maxFiles: '30d'
        }),
        // 综合日志 - 按天轮转
        new DailyRotateFile({
            filename: path.join(__dirname, '../logs/combined-%DATE%.log'),
            datePattern: 'YYYY-MM-DD',
            zippedArchive: true,
            maxSize: '20m',
            maxFiles: '30d'
        }),
        // 控制台输出 - 开发环境更友好
        new winston.transports.Console({
            format: format.combine(
                format.colorize(),
                format.printf(({ timestamp, level, message, stack }) => {
                    let msg = `${timestamp} [${level}]: `;
                    if (typeof message === 'object') {
                        msg += JSON.stringify(message, null, 2);
                    } else {
                        msg += message;
                    }
                    if (stack) {
                        msg += `\n${stack}`;
                    }
                    return msg;
                })
            )
        })
    ]
});

// 开发环境增加调试日志
if (process.env.NODE_ENV === 'development') {
    logger.add(new winston.transports.File({
        level: 'debug',
        filename: path.join(__dirname, '../logs/debug.log'),
        format: format.combine(
            format.prettyPrint(),
            format.splat()
        )
    }));
}

// 动态调整日志级别
logger.setLevel = (level) => {
    logger.transports.forEach(transport => {
        if (transport.setLevel) {
            transport.level = level;
        }
    });
    logger.level = level;
};

// 添加请求日志中间件
logger.requestLogger = (req, res, next) => {
    const start = Date.now();
    const { method, originalUrl, ip, body } = req;

    res.on('finish', () => {
        const { statusCode } = res;
        const duration = Date.now() - start;
        
        logger.info('HTTP请求', {
            method,
            url: originalUrl,
            ip,
            status: statusCode,
            duration: `${duration}ms`,
            body: method !== 'GET' ? body : undefined
        });
    });

    next();
};

module.exports = logger;